var Node = function(val){
    this.val=val
    this.next=null
}


var MyLinkedList = function() {
    this.head=null
    this.length=0
};

/** 
 * @param {number} index
 * @return {number}
 */
MyLinkedList.prototype.get = function(index) {
    if(index+1>this.length){
        return -1
    }
    let currNode = this.head
    while(index>0){
        currNode=currNode.next
        index--
    }
    return currNode.val
};

/** 
 * @param {number} val
 * @return {void}
 */
MyLinkedList.prototype.addAtHead = function(val) {
   let newNode = new Node(val)
   newNode.next=this.head
   this.head=newNode
   this.length++
};

/** 
 * @param {number} val
 * @return {void}
 */
MyLinkedList.prototype.addAtTail = function(val) {
    let newNode = new Node(val)
    let currNode = this.head
    if(!currNode) {
        this.head=newNode; 
        this.length++;
        return
    }
    while(currNode){
        if(currNode.next==null){
            break
        }
        currNode=currNode.next
        
    }
    currNode.next=newNode
    this.length++
};

/** 
 * @param {number} index 
 * @param {number} val
 * @return {void}
 */
MyLinkedList.prototype.addAtIndex = function(index, val) {
    if(index==0) {this.addAtHead(val);return}
    if(index==this.length) {this.addAtTail(val);return}
    if(index+1>this.length) return
    let currNode = this.head
    while(index>1){
        currNode=currNode.next
        index--
    }
    let newNode=new Node(val)
    newNode.next=currNode.next
    currNode.next=newNode
    this.length++
};

/** 
 * @param {number} index
 * @return {void}
 */
MyLinkedList.prototype.deleteAtIndex = function(index) {
    let currNode = this.head
    if(index+1>this.length) return
    if(index==0) {
        this.head=currNode.next
        this.length--
        return
    }
    
    while(index>1){
        currNode=currNode.next
        index--
    }
    currNode.next=currNode.next.next
    this.length--
};

module.exports={MyLinkedList,Node}

// let List = new MyLinkedList()
// List.addAtHead(1)
// List.addAtTail(3)
// console.log(List.head);
// List.addAtIndex(1,2)
// console.log(List.head);
// console.log(List.get(1));
// List.deleteAtIndex(1)
// console.log(List.get(1));

// console.log(List.head,List.length);
